#!/bin/sh
#
# Perform necessary datadog-iot-agent setup steps before package is installed.
#
# .rpm: STEP 2 of 6

INSTALL_DIR=/opt/datadog-agent
SERVICE_NAME=datadog-agent

set -e

if [ -f "/lib/systemd/system/$SERVICE_NAME.service" ] || [ -f "/usr/lib/systemd/system/$SERVICE_NAME.service" ]; then
    # Stop an already running agent
    # Only supports systemd and upstart
    if command -v systemctl >/dev/null 2>&1; then
        systemctl stop $SERVICE_NAME || true
    elif command -v initctl >/dev/null 2>&1; then
        initctl stop $SERVICE_NAME || true
    else
        echo "[ WARNING ]\tCannot detect a supported init system. The datadog-iot-agent package only provides service files for systemd and upstart."
    fi
fi

# Set up `dd-agent` user and group
if ! getent group dd-agent >/dev/null; then
    groupadd -r dd-agent
fi
if ! getent passwd dd-agent >/dev/null; then
    useradd -r -M -g dd-agent -d $INSTALL_DIR -s /sbin/nologin -c "Datadog Agent" dd-agent
    if ! usermod -L dd-agent; then
        echo "[ WARNING ]\tCannot lock the 'dd-agent' user account"
    fi
fi

exit 0
